﻿using System;
using System.Web;
using System.Web.SessionState;
using System.Diagnostics;
using FiftyOne.Foundation.Mobile.Detection;

namespace SelArom.Net.Sitefinity.HttpModules
{
	/// <summary>
	/// HttpModule to detect if user is on a Mobile Device
	/// </summary>
	public class BrowserDetectModule : DetectorModule, IHttpModule, IRequiresSessionState
	{
		// In the Init function, register for HttpApplication 
		// events by adding your handlers.
		public new void Init(HttpApplication application)
		{
			base.Init(application);
			application.PostAcquireRequestState += Application_PostAcquireRequestState;
		}

		// Your BeginRequest event handler.
		private void Application_PostAcquireRequestState(Object source, EventArgs e)
		{
			var Context = HttpContext.Current;
			var Session = Context.Session;

			// skip unnecessary requests
			if (Telerik.CmsContext.IsCrawlerRequest) return;

			// get requested page
			var url = Context.Request.Path;
			var urlLowered = url.ToLower();

			// exclude non-pages
			if (!(urlLowered == "/sitefinity/cmsentrypoint.aspx") || urlLowered.Contains("ashx")) return;

			// user requested change?
			if (!string.IsNullOrEmpty(Context.Request.QueryString["mobile"]))
			{
				// save user setting
				Session["mobile"] = Context.Request.QueryString["mobile"] == "1";

				// 301 redirect to avoid multiple seo links
				var oldUrl = Context.Request.Url.ToString().ToLower();
				var oldPath = Context.Request.Url.PathAndQuery.ToLower();
				var newPath = Context.Request.RawUrl.ToLower().Replace("mobile=0", "").Replace("mobile=1", "");
				var newUrl = oldUrl.Replace(oldPath, newPath);

				// if this was the only qstring clear it
				if (newUrl.EndsWith("?") || newUrl.EndsWith("&")) newUrl = newUrl.Remove(newUrl.Length - 1);

				// redirect to lowercase
				Context.Response.Clear();
				Context.Response.Status = "301 Moved Permanently";
				Context.Response.AddHeader("Location", newUrl);
				Context.Response.End();
				return;
			}

			// if set skip check
			if (Session == null || Session["mobile"] != null) return;

			Session["mobile"] = Context.Request.Browser.IsMobileDevice;
		}
	}
}